#include "Echoclient.hpp"
#include "Common.hpp"

#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <cstdlib>

#include <string.h>

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        // 说明不是按照格式
        std::cerr << "Usage" << argv[0] << "is wrong!" << "\n";

        exit(1);
    }

    std::string _serverip = argv[1];
    uint16_t _serverport = std::stoi(argv[2]);

    int _sockfd = ::socket(
        AF_INET,
        SOCK_DGRAM,
        0);

    if (_sockfd < 0)
    {
        std::cerr << "socket error!" << std::endl;
        exit(2);
    }

    // 填充 server 的信息

    struct sockaddr_in _server;
    memset(&_server, 0, sizeof(_server));

    _server.sin_addr.s_addr = ::inet_addr(_serverip.c_str());
    _server.sin_family = AF_INET;
    _server.sin_port = htons(_serverport);

    while (true)
    {
        std::cout << "Please Enter#";
        std::string _message;
        std::getline(std::cin, _message);

        ssize_t _n = ::sendto(
            _sockfd,
            _message.c_str(), _message.size(),
            0, CONV(&_server), sizeof(_server));

        struct sockaddr_in _tmp;
        socklen_t _len = sizeof(_tmp);

        char _buffer[1024];
        _n = ::recvfrom(_sockfd,
                        _buffer, sizeof(_buffer),
                        0, CONV(&_tmp), &_len);

        if (_n > 0)
        {
            // 说明读到消息了
            _buffer[_n] = 0;
            std::cout << _buffer << std::endl;
        }
    }

    return 0;
}